var startTime = new Date().getTime();
var productId = $.getUrlParam('productid');
var mainData = JSON.parse(localStorage.getItem('mainData'));
//后台读取结果集
var _data = {}

//保存最后的组合结果信息
var SKUResult = {};
//获得对象的key
function getObjKeys(obj) {
    if (obj !== Object(obj)) throw new TypeError('Invalid object');
    var keys = [];
    for (var key in obj)
        if (Object.prototype.hasOwnProperty.call(obj, key))
            keys[keys.length] = key;
    return keys;
}

//把组合的key放入结果集SKUResult
function add2SKUResult(combArrItem, sku) {
    combArrItem.sort(function (value1, value2) {
        return parseInt(value1) - parseInt(value2);
    });
    var key = combArrItem.join(",");
    if (SKUResult[key]) { //SKU信息key属性·
        SKUResult[key].count += sku.moq;
        SKUResult[key].prices.push(sku.totalPrice);
    } else {
        SKUResult[key] = {
            count: sku.moq,
            prices: [sku.totalPrice]
        };
    }
    // console.log(SKUResult)
}

//初始化得到结果集
function initSKU() {
    var i, j, skuKeys;
    post({
        url: '/customizeOrder/find/attrIds',
        data: {
            productId: productId
        },
        success: function (result) {
            _data = result;
            skuKeys = getObjKeys(_data);
            for (i = 0; i < skuKeys.length; i++) {
                var skuKey = skuKeys[i]; //一条SKU信息key
                var sku = _data[skuKey]; //一条SKU信息value
                var skuKeyAttrs = skuKey.split(","); //SKU信息key属性值数组
                skuKeyAttrs.sort(function (value1, value2) {
                    return parseInt(value1) - parseInt(value2);
                });
                var len = skuKeyAttrs.length;


                //对每个SKU信息key属性值进行拆分组合
                var combArr = arrayCombine(skuKeyAttrs);
                for (j = 0; j < combArr.length; j++) {
                    add2SKUResult(combArr[j], sku);
                }
                
                //结果集接放入SKUResult
                SKUResult[skuKeyAttrs.toString()] = {
                    count: sku.moq,
                    prices: [sku.totalPrice]
                }
            }
        }
    })
    // console.log(SKUResult)


}

/**
 * 从数组中生成指定长度的组合
 */
function arrayCombine(targetArr) {
    if (!targetArr || !targetArr.length) {
        return [];
    }

    var len = targetArr.length;
    var resultArrs = [];

    // 所有组合
    for (var n = 1; n < len; n++) {
        var flagArrs = getFlagArrs(len, n);
        while (flagArrs.length) {
            var flagArr = flagArrs.shift();
            var combArr = [];
            for (var i = 0; i < len; i++) {
                flagArr[i] && combArr.push(targetArr[i]);
            }
            resultArrs.push(combArr);
        }
    }

    return resultArrs;
}


/**
 * 获得从m中取n的所有组合
 */
function getFlagArrs(m, n) {
    if (!n || n < 1) {
        return [];
    }

    var resultArrs = [],
        flagArr = [],
        isEnd = false,
        i, j, leftCnt;

    for (i = 0; i < m; i++) {
        flagArr[i] = i < n ? 1 : 0;
    }

    resultArrs.push(flagArr.concat());

    while (!isEnd) {
        leftCnt = 0;
        for (i = 0; i < m - 1; i++) {
            if (flagArr[i] == 1 && flagArr[i + 1] == 0) {
                for (j = 0; j < i; j++) {
                    flagArr[j] = j < leftCnt ? 1 : 0;
                }
                flagArr[i] = 0;
                flagArr[i + 1] = 1;
                var aTmp = flagArr.concat();
                resultArrs.push(aTmp);
                if (aTmp.slice(-n).join("").indexOf('0') == -1) {
                    isEnd = true;
                }
                break;
            }
            flagArr[i] == 1 && leftCnt++;
        }
    }
    return resultArrs;
}


//初始化用户选择事件
$(function () {
    initSKU();
    var endTime = new Date().getTime();
    $('#init_time').text('init sku time: ' + (endTime - startTime) + " ms");
    // $('.sku').each(function () {
    //     var self = $(this);
    //     var attr_id = self.attr('attr_id');
    //     if (!SKUResult[attr_id]) {
    //         // self.attr('disabled', 'disabled');
    //         self.addClass('_dash')
    //     }
    // });
    $('.standardItem').delegate('.sku', 'click', function () {
        var self = $(this);
        console.log(self)
        if(self.hasClass('_dash')){
            return;
        }
        //选中自己，兄弟节点取消选中
        self.toggleClass('active').siblings().removeClass('active');

        //已经选择的节点
        var selectedObjs = $('.active');

        if (selectedObjs.length) {
            //获得组合key价格
            var selectedIds = [];
            selectedObjs.each(function () {
                selectedIds.push($(this).attr('attr_id'));
            });
            selectedIds.sort(function (value1, value2) {
                return parseInt(value1) - parseInt(value2);
            });
            var len = selectedIds.length;
            // console.log(SKUResult[selectedIds.join(',')])
            var prices = SKUResult[selectedIds.join(',')].prices;
            var maxPrice = Math.max.apply(Math, prices);
            var minPrice = Math.min.apply(Math, prices);
            var oldPrice = mainData['minPrice'];
            $('._minPrice').text(maxPrice > minPrice ? oldPrice : oldPrice);
            

            //用已选中的节点验证待测试节点 underTestObjs
            $(".sku").not(selectedObjs).not(self).each(function () {
                var siblingsSelectedObj = $(this).siblings('.active');
                var testAttrIds = []; //从选中节点中去掉选中的兄弟节点
                if (siblingsSelectedObj.length) {
                    var siblingsSelectedObjId = siblingsSelectedObj.attr('attr_id');
                    for (var i = 0; i < len; i++) {
                        (selectedIds[i] != siblingsSelectedObjId) && testAttrIds.push(selectedIds[i]);
                    }
                } else {
                    testAttrIds = selectedIds.concat();
                }
                testAttrIds = testAttrIds.concat($(this).attr('attr_id'));
                testAttrIds.sort(function (value1, value2) {
                    return parseInt(value1) - parseInt(value2);
                });
                if (!SKUResult[testAttrIds.join(',')]) {
                    $(this).addClass('_dash').removeClass('active');
                    // $(this).attr('disabled', 'disabled').removeClass('active');
                } else {
                    $(this).removeClass('_dash');
                }
            });
        } else {
            //设置默认价格
            $('_minPrice').text('--');
            //设置属性状态
            $('.sku').each(function () {
                SKUResult[$(this).attr('attr_id')] ? $(this).removeClass('_dash') : $(this).addClass('_dash').removeClass('active');
            })
        }
    });
});